package com.woan.api.idao.dao;

import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.woan.api.idao.SysVideoIDAO;
import com.woan.api.model.SysAdmininfo;
import com.woan.api.model.SysVideo;
import com.woan.api.model.SysVideoBasic;
import com.woan.api.vo.VClientvideoList;
import com.woan.api.vo.VOnevideo;
import com.woan.api.vo.VpositionList;
import com.woan.api.vo.VvideoList;

/**
 * A data access object (DAO) providing persistence and search support for SysVideo entities. Transaction control of the save(), update() and delete() operations can directly support Spring container-managed transactions or they can be augmented to handle user-managed Spring transactions. Each of
 * these methods provides additional information for how to configure it for the desired type of transaction control.
 * 
 * @see com.woan.api.model.SysVideo
 * @author MyEclipse Persistence Tools
 */

public class SysVideoDAO extends HibernateDaoSupport implements SysVideoIDAO {
	// 根据视频id获取视频对象
	public SysVideoBasic get(String videoid) {
		return (SysVideoBasic) this.getHibernateTemplate().get(SysVideoBasic.class, videoid);
	}

	// 根据数据库生成的SysVideo实体类返回列表
	public List<SysVideoBasic> FindLiveVideoByGroup(String groupid, Integer beginIndex, Integer endIndex) {
		StringBuffer hql = new StringBuffer("from SysVideo");
		hql.append(" where rid='" + groupid + "' and statusM3u8 = 0 and isdel = '1' order by beginTime desc ");
		Session session = this.getSession();
		try {
			Query query = session.createQuery(hql.toString());
			query.setFirstResult(beginIndex);
			query.setMaxResults(endIndex);
			List<SysVideoBasic> list = query.list();

			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 根据自定义返回的实体返回搜索列表
	public List<VvideoList> FindVSerachVideoByDetail(String groupid, Integer beginIndex, Integer endIndex, Map<String, String> map) {
		StringBuffer buffer = new StringBuffer("select vid, pictureM3u8 as picture, userName, address, detail,videoSize,videoLength,videoPathM3u8 as videoPath,beginTime,endTime,title," + " longitude, latitude, countrycode, countryname,province,city,counties" + " from sys_video" + " where rid='" + groupid + "'  and statusM3u8 = 1 and isdel = '1' ");
		if (map.get("paishename").toString() != null && !map.get("paishename").equals(""))
			buffer.append(" and userName like '%" + map.get("paishename").toString() + "%' ");
		if (map.get("title").toString() != null && !map.get("title").equals(""))
			buffer.append(" and title like '%" + map.get("title").toString() + "%' ");
		if (map.get("detail").toString() != null && !map.get("detail").equals("")) {
			buffer.append(" and detail like '%" + map.get("detail").toString() + "%' ");
		}

		buffer.append(" order by beginTime desc ");
		// System.out.println(buffer.toString());
		try {
			Query query = getSession().createSQLQuery(buffer.toString()).setResultTransformer(Transformers.aliasToBean(VvideoList.class));
			query.setFirstResult(beginIndex);
			query.setMaxResults(endIndex);
			List<VvideoList> list = query.list();

			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 编辑视频描述
	public String EditVideos(String videoid, String videodetail) {
		SysVideoBasic sysvideo = this.get(videoid);

		String flag = "0";
		if (sysvideo != null) {
			try {
				sysvideo.setDetail(videodetail);
				this.getHibernateTemplate().saveOrUpdate(sysvideo);
			} catch (Exception e) {
				e.printStackTrace();
				flag = "1";
			}
		}
		return flag;
	}

	public String EditVideos(String vid, String title, String address, String longitude, String latitude, String detail) {
		SysVideoBasic sysvideo = this.get(vid);
		String flag = "0";
		if (sysvideo != null) {
			if (title != null && !title.equals(""))
				sysvideo.setTitle(title);
			if (address != null && !address.equals(""))
				sysvideo.setAddress(address);
			if (detail != null && !detail.equals(""))
				sysvideo.setDetail(detail);
			if (latitude != null && !latitude.equals(""))
				sysvideo.setLatitude(latitude);
			if (longitude != null && !longitude.equals(""))
				sysvideo.setLongitude(longitude);
		} else {
			sysvideo = new SysVideoBasic();
			sysvideo.setVid(vid);
			if (title != null && !title.equals(""))
				sysvideo.setTitle(title);
			if (address != null && !address.equals(""))
				sysvideo.setAddress(address);
			if (detail != null && !detail.equals(""))
				sysvideo.setDetail(detail);
			if (latitude != null && !latitude.equals(""))
				sysvideo.setLatitude(latitude);
			if (longitude != null && !longitude.equals(""))
				sysvideo.setLongitude(longitude);
		}
		try {
			this.getHibernateTemplate().save(sysvideo);
		} catch (Exception e) {
			e.printStackTrace();
			flag = "1";
		}
		return flag;
	}

	// 删除视频
	public boolean DeleteVideos(String videoid) {
		Session session = this.getSession();
		StringBuffer hql = new StringBuffer(" update sys_video set isdel='0' where vid='" + videoid + "' ");
		// System.out.println(hql.toString());
		session.createSQLQuery(hql.toString()).executeUpdate();
		return true;
	}

	// 位置信息
	public List<VpositionList> FindVVideoPostion(String groupid, String type) {
		StringBuffer buffer = new StringBuffer("SELECT ad.uid,ad.nickName as \"nickName\" ,ad.userName as \"userName\",ad.longitude,ad.latitude,ad.province,ad.city,ad.counties," + "ad.countryname,ad.updateTime as \"updateTime\",v.address,v.videoLength as \"videoLength\",v.videoPath as \"videoPath\",v.videoSize as \"videoSize\",v.picture,v.title," + "v.beginTime as \"beginTime\",v.endTime   as \"endTime\" FROM sys_admininfo ad LEFT JOIN (SELECT b.uid,b.address,a.videoLength,a.videoPath,a.videoSize,a.picture,b.title,a.beginTime,a.endTime FROM sys_video a ,sys_video_basic b where a.vid=b.vid and a.videotype='" + type + "' and a.status='0' ) v ON ad.uid = v.uid " + "where ad.rid='" + groupid + "' and ad.type='3' and ad.isdel='1' order by ad.updateTime desc");
		System.out.println(buffer.toString());
		try {
			Query query = getSession().createSQLQuery(buffer.toString()).setResultTransformer(Transformers.aliasToBean(VpositionList.class));

			List<VpositionList> list = query.list();

			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 手机客户端---根据组id和视频类型返回自定义的直播列表实体
	public List<VClientvideoList> FindVCLiveVideoByGroup(String groupid, String type, Integer beginIndex, Integer endIndex) {
		StringBuffer buffer = new StringBuffer("select v.vid, v.picture,v.status, vb.userName as \"userName\", vb.address, vb.detail,v.videoPath as \"videoPath\", v.beginTime as \"beginTime\",  v.endTime as \"endTime\" ,vb.title,a.nickName as \"nickName\" ");
		buffer.append(" from sys_video_basic vb,sys_video v,sys_admininfo a");
		buffer.append(" where vb.rid='" + groupid + "' and vb.vid=v.vid and a.uid=vb.uid and v.status= 0 and v.videotype='" + type + "' and v.isdel = '1' order by v.beginTime desc ");
		//buffer.append(" where vb.rid='" + groupid + "' and vb.vid=v.vid and a.uid=vb.uid and v.status= 0 and  v.isdel = '1' order by v.beginTime desc ");
		System.out.println(buffer.toString());
		try {
			Query query = getSession().createSQLQuery(buffer.toString()).setResultTransformer(Transformers.aliasToBean(VClientvideoList.class));
			if (beginIndex != 0) {
				query.setFirstResult(beginIndex);
				query.setMaxResults(endIndex);
			}
			List<VClientvideoList> list = query.list();
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// pad端----根据自定义返回的实体返回直播列表
	public List<VvideoList> FindVLiveVideoByGroup(String groupid, String type, Integer beginIndex, Integer endIndex) {
		StringBuffer buffer = new StringBuffer("select v.vid, v.picture, vb.userName as \"userName\" , vb.address, vb.detail,v.videoPath as \"videoPath\",v.beginTime as \"beginTime\",v.endTime  as \"endTime\",vb.title,a.nickName as \"nickName\" ");
		buffer.append(" from sys_video_basic vb,sys_video v,sys_admininfo a");
		buffer.append(" where vb.rid='" + groupid + "' and vb.vid=v.vid and a.uid=vb.uid and v.status= 0 and v.videotype='" + type + "' and v.isdel = '1' order by v.beginTime desc ");
		//buffer.append(" where vb.rid='" + groupid + "' and vb.vid=v.vid and a.uid=vb.uid and v.status= 0  and v.isdel = '1' order by v.beginTime desc ");
		System.out.println(buffer.toString());
		try {
			Query query = getSession().createSQLQuery(buffer.toString()).setResultTransformer(Transformers.aliasToBean(VvideoList.class));
			if (beginIndex != 0) {
				query.setFirstResult(beginIndex);
				query.setMaxResults(endIndex);
			}
			List<VvideoList> list = query.list();

			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 手机客户端---根据组id和视频类型返回自定义的历史列表实体
	public List<VClientvideoList> FindVCHistoryVideoByGroup(String groupid, String type, Integer beginIndex, Integer endIndex) {
		StringBuffer buffer = new StringBuffer("select v.vid, v.picture,v.status, vb.createTime as \"createTime\" ,vb.userName as \"userName\" , vb.address, vb.detail,v.videoPath as \"videoPath\" ,v.beginTime as \"beginTime\",v.endTime as \"endTime\" ,v.videoLength  as \"videoLength\",vb.title,a.nickName as \"nickName\" ");
		buffer.append(" from sys_video_basic vb,sys_video v,sys_admininfo a");
		//注释掉 videoType 类型 
		buffer.append(" where vb.rid='" + groupid + "' and vb.vid=v.vid and a.uid=vb.uid and v.status= 1 and v.videotype='"+type+"' and v.isdel = '1' order by v.beginTime desc ");
		//buffer.append(" where vb.rid='" + groupid + "' and vb.vid=v.vid and a.uid=vb.uid and v.status= 1  and v.isdel = '1' order by v.beginTime desc ");
		System.out.println(buffer.toString());
		try {
			Query query = getSession().createSQLQuery(buffer.toString()).setResultTransformer(Transformers.aliasToBean(VClientvideoList.class));
			query.setFirstResult(beginIndex);
			query.setMaxResults(endIndex);
			List<VClientvideoList> list = query.list();

			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// pad根据自定义返回的实体返回历史列表
	public List<VvideoList> FindVHistoryVideoByGroup(String groupid, String type, Integer beginIndex, Integer endIndex) {
		StringBuffer buffer = new StringBuffer("select v.vid, v.picture, vb.createTime as \"createTime\",vb.userName as \"userName\", vb.address, vb.detail,v.videoPath as \"videoPath\",v.beginTime as \"beginTime\" ,v.endTime as \"endTime\" ,v.videoLength as \"videoLength\",vb.title,a.nickName as \"nickName\" ");
		buffer.append(" from sys_video_basic vb,sys_video v,sys_admininfo a");
		buffer.append(" where vb.rid='" + groupid + "' and vb.vid=v.vid and a.uid=vb.uid and v.status= 1 and v.videotype='" + type + "' and v.isdel = '1' order by v.beginTime desc ");
		//buffer.append(" where vb.rid='" + groupid + "' and vb.vid=v.vid and a.uid=vb.uid and v.status= 1  and v.isdel = '1' order by v.beginTime desc ");
		System.out.println(buffer.toString());
		try {
			Query query = getSession().createSQLQuery(buffer.toString()).setResultTransformer(Transformers.aliasToBean(VvideoList.class));
			query.setFirstResult(beginIndex);
			query.setMaxResults(endIndex);
			List<VvideoList> list = query.list();
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public VOnevideo FindVOneVideoByVid(String vid, String type) {
		StringBuffer buffer = new StringBuffer("select vb.userName as \"userName\", v.videoPath as \"videoPath\",v.beginTime as \"beginTime\" ,v.status ");
		//buffer.append(" from sys_video_basic vb,sys_video v");
		buffer.append(" where vb.vid='" + vid + "' and vb.vid=v.vid and v.videotype='" + type + "'");
		buffer.append(" where vb.vid='" + vid + "' and vb.vid=v.vid  ");
		System.out.println(buffer.toString());
		try {
			Query query = getSession().createSQLQuery(buffer.toString()).setResultTransformer(Transformers.aliasToBean(VOnevideo.class));
			List<VOnevideo> list = query.list();

			return list.get(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 手机客户端---根据用户id和视频类型返回自定义的我的列表实体
	public List<VClientvideoList> FindVMyVideoByUid(String uid, String type, Integer beginIndex, Integer endIndex) {
		StringBuffer buffer = new StringBuffer("select v.vid, v.picture,v.status, vb.userName as \"userName\" , vb.address , vb.detail,v.videoPath as \"videoPath\",v.beginTime as \"beginTime\",v.endTime as \"endTime\",v.videoLength as \"videoLength\" ,vb.title,a.nickName as \"nickName\" ");
		buffer.append(" from sys_video_basic vb,sys_video v,sys_admininfo a");
		buffer.append(" where vb.uid='" + uid + "' and vb.vid=v.vid and a.uid=vb.uid and v.status= 1 and v.videotype='" + type + "' and v.isdel = '1' order by v.beginTime desc ");
		//buffer.append(" where vb.uid='" + uid + "' and vb.vid=v.vid and a.uid=vb.uid and v.status= 1  and v.isdel = '1' order by v.beginTime desc ");
		System.out.println(buffer.toString());
		try {
			Query query = getSession().createSQLQuery(buffer.toString()).setResultTransformer(Transformers.aliasToBean(VClientvideoList.class));
			query.setFirstResult(beginIndex);
			query.setMaxResults(endIndex);
			List<VClientvideoList> list = query.list();

			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 手机客户端---历史列表数量
	public int FindHistoryVideoCountByGroup(String groupid, String type) {
		String hql = "from SysVideo where rid='" + groupid + "' and status=1 and videotype='" + type + "' and isdel = '1'";
		//String hql = "from SysVideo where rid='" + groupid + "' and status=1  and isdel = '1'";
		try {
			List list = this.getHibernateTemplate().find(hql);
			if (list.size() > 0)
				return list.size();
			else
				return 0;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	// 手机客户端---我的视频列表数量
	public int FindMyVideoCountByUid(String uid, String type) {
//		String hql = "from SysVideo where uid='" + uid + "' and status = 1 and isdel = '1'  and videotype='" + type + "'";
		String hql = "from SysVideo where uid='" + uid + "' and status = 1 and isdel = '1' ";
		try {
			List list = this.getHibernateTemplate().find(hql);
			if (list.size() > 0)
				return list.size();
			else
				return 0;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	// 更新视频状态-----拍摄之前首先将之前的未结束的视频结束
	public void UpdateVideoState(String uid,String vid) {
		try {
//			String hqlString =" from SysVideo v left join SysVideoBasic b on b.vid=v.vid and v.status=0 and b.uid='"+uid+"'  ";
			String hqlString =" from SysVideo v where v.status=0 and v.vid!='"+vid+"' ";
			List<SysVideo> list = this.getHibernateTemplate().find(hqlString);
			if (list!=null&&list.size()>0) {
				for (SysVideo sysVideo : list) {
					String hqlString2 ="from SysVideoBasic where vid='"+sysVideo.getVid()+"' and  uid='"+uid+"' ";
					List find = getHibernateTemplate().find(hqlString2);
					if (find!=null&&find.size()>0) {
						sysVideo.setStatus(1);
						getHibernateTemplate().update(sysVideo);
					}
				}
			}
			/*String hql = "update sys_video set status = 1 where vid=(select v.vid from sys_video as v ,sys_video_basic as b where v.vid=b.vid and  b.uid='"+uid+"' and  v.status=0)";
			Session session = this.getSession();
			Transaction tran = session.beginTransaction();
			session.createSQLQuery(hql.toString()).executeUpdate();
			tran.commit(); 
			session.flush();
			session.close();*/
			//session.clear();
		} catch (Exception e) {
			System.err.println("更新时候报错了。还是插入时候报错呢");
			e.printStackTrace();;
		}
	}

	// 插入新视频
	public void InsertVideo(SysVideo sysVideo) {
		String videoPath = sysVideo.getVideoPath();
		String picture = sysVideo.getPicture();
		// 执行url地址的替换 http://192.168.0.201:3339/mobile/1-feceb62728de.flv
		// String url = "http://192.168.0.201:3339/mobile/1-feceb62728de.flv";
		/*if (!videoPath.equals("")) {
			System.err.println("开始进行视频的替换");
			String substring = videoPath.substring(videoPath.lastIndexOf(":"));
			System.err.println("修改后的ip地址是" + substring);
			sysVideo.setVideoPath(substring);
		}
		if (!picture.equals("")) {
			System.err.println("开始进行照片的url");
			String substring = videoPath.substring(picture.lastIndexOf(":"));
			System.err.println("修改后的ip地址是" + substring);
			sysVideo.setPicture(substring);
		}*/

		
		
		//String sql = "insert into sys_video (seqid,vid, picture, status, videoSize , videoLength , videoPath , beginTime , endTime , videoType  , isdel) values" + " ("+System.currentTimeMillis()+",'" + sysVideo.getVid() + "','" + sysVideo.getPicture() + "','" + sysVideo.getStatus() + "','" + sysVideo.getVideoSize() + "','" + sysVideo.getVideoLength() + "','" + sysVideo.getVideoPath() + "','" + sysVideo.getBeginTime() + "','" + sysVideo.getEndTime() + "','" + sysVideo.getVideoType() + "','" + sysVideo.getIsdel() + "')";
		// String sql="insert into sys_video (vid, picture, status, videoSize, videoLength, videoPath, beginTime, endTime, videoType, isdel) values" +
		// " ('1','','0','','','','','','','')";
		sysVideo.setSeqid(System.currentTimeMillis());
		getHibernateTemplate().save(sysVideo);
		
		
		
		/*System.out.println("插入视频时候的Sql语句" + sql);
		Session session = this.getSession();
		Transaction tx = session.beginTransaction();
		System.out.println(session);
		try {
			tx.begin();
			session.createSQLQuery(sql.toString()).executeUpdate();
			 session.flush();
			tx.commit();
			System.out.println("插入完成");
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}*/
		// try {
		// getHibernateTemplate().save(sysVideo);
		// } catch (Exception re) {
		// re.printStackTrace();
		// System.out.println(re);
		// //throw re;
		// }
	}

	// 手机客户端---视频视频id和视频类型查找视频信息
	// 视频服务器接口也使用此方法
	public SysVideo FindVideoByVidAndType(String vid, String videotype) {
		
		String hql = "from SysVideo where vid='" + vid + "' and videotype='" + videotype + "' ";
		
		
		List<SysVideo> list = this.getHibernateTemplate().find(hql);
		if (list!=null&&list.size()>0) {
			return list.get(0);
		}else {
			return null;
		}
		
	/*	StringBuffer buffer = new StringBuffer("select seqid,picture,status,beginTime as \"beginTime\",videoSize as \"videoSize\",endTime as \"endTime\",videoLength as \"videoLength\",videoType as \"videoType\",videoPath as \"videoPath\" ,isdel from sys_video ");
		buffer.append(" where vid='" + vid + "'  and videotype='" + videotype + "' ");
		//buffer.append(" where vid='" + vid + "'   ");
		System.out.println(buffer.toString());
		try {
			Query query = getSession().createSQLQuery(buffer.toString()).setResultTransformer(Transformers.aliasToBean(SysVideo.class));
			List<SysVideo> list = query.list();
			if (list.size() == 0)
				return null;
			else
				return list.get(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;*/
	}

	public List<SysVideo> FindAllVideoByVidAndType(String vid, String videotype) {
		String hqlString ="from SysVideo where vid='"+vid+"' and videoType='"+videotype+"' ";
		//String hqlString ="from SysVideo where vid='"+vid+"'  ";
		List<SysVideo> list = this.getHibernateTemplate().find(hqlString);
		return list;
		
		
		/*StringBuffer buffer = new StringBuffer("select  beginTime as \"beginTime\", endTime as \"endTime\", videoSize as \"videoSize\", videoLength as \"videoLength\" ,videoPath as \"videoPath\" ,videoType as \"videoType\" from sys_video ");
		buffer.append(" where vid='" + vid + "'  and videotype='" + videotype + "' ");
		System.out.println(buffer.toString());
		try {
			Query query = getSession().createSQLQuery(buffer.toString()).setResultTransformer(Transformers.aliasToBean(SysVideo.class));
			List<SysVideo> list = query.list();
			if (list.size() == 0)
				return null;
			else
				return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;*/
	}

	// 更新视频
	public void UpdateVideo(SysVideo sysVideo) {
		try {
			String videoPath = sysVideo.getVideoPath();
			sysVideo.setPicture(videoPath+".jpg");
			/*if (!videoPath.equals("")) {
				System.err.println("开始进行视频的替换");
				String substring = videoPath.substring(videoPath.lastIndexOf(":"));
				System.err.println("修改后的ip地址是" + substring);
				sysVideo.setVideoPath(substring);
			}*/
			
			this.getHibernateTemplate().update(sysVideo);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void deletVideo(SysVideo video_task) {
		try {
			this.getHibernateTemplate().delete(video_task);
			System.out.println("删除任务—" + video_task.getVideoType() + "///////////////////////");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void InsertVideo_flv(SysVideo sysVideo, SysAdmininfo user) {
		//String hql = "update sys_video set status = 1 where vid=(select v.vid from sys_video as v ,sys_video_basic as b where v.vid=b.vid and  b.uid='"+user.getUid()+"' and  v.status=0)";
		//String sql = "insert into sys_video (seqid,vid, picture, status, videoSize , videoLength , videoPath , beginTime , endTime , videoType  , isdel) values" + " ("+System.currentTimeMillis()+",'" + sysVideo.getVid() + "','" + sysVideo.getPicture() + "','" + sysVideo.getStatus() + "','" + sysVideo.getVideoSize() + "','" + sysVideo.getVideoLength() + "','" + sysVideo.getVideoPath() + "','" + sysVideo.getBeginTime() + "','" + sysVideo.getEndTime() + "','" + sysVideo.getVideoType() + "','" + sysVideo.getIsdel() + "')";
		
		try {
			
			sysVideo.setSeqid(System.currentTimeMillis());
			getHibernateTemplate().save(sysVideo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	/*	Session session = this.getSession();
		Transaction tx = session.beginTransaction();
		try {
			tx.begin();
			//session.createSQLQuery(hql).executeUpdate();
			session.createSQLQuery(sql).executeUpdate();
			 session.flush();
			tx.commit();
			System.out.println("插入完成");
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}*/
	}
}